# This file is for setting up a virtual environment for development with the
# packages specified in the requirements.txt file

# All strings should end in a space character

# need to catch doesNotExist errors for deleting
# need to catch not enough permissions errors as well
# prompt for a port

def installLinux(pathToVirtualenvFile,veFlags,veDestDir,pipFlags):
    pathToPython = ".virtualenv/bin/python "
    pathToPip = ".virtualenv/bin/pip "
    pathToManage = "project/manage.py "
    if os.path.isdir(veDestDir):
        response = input('.virtualenv folder is already created, erase and create new? (y/n): ')
        if y in response:
            shutil.rmtree('.virtualenv')
            os.system("python " + pathToVirtualenvFile + veFlags + veDestDir)
            os.system(pathToPython + pathToPip + "install " + pipFlags)
    else:
        os.system("python " + pathToVirtualenvFile + veFlags + veDestDir)
        os.system(pathToPython + pathToPip + "install " + pipFlags)
    os.system(pathToPython + pathToManage + "syncdb")
    

def setupApacheInUbuntu():
    conf = raw_input('Warning to setup Apache this must be run as root do you want to continue Y/n: ')  
    confVar = str(conf)
    if (confVar == 'Y' or confVar == 'Yes' or confVar == 'yes'):
        trunkPath = os.path.abspath('%s' % os.getcwd()) + '/'
        tmpFile = open('project/apache/otg.apache.conf.tmp','r')
        apacheConf = open('project/apache/otg.apache.conf','w')
        port = input('Enter the desired port number for hosting: ')    
        port = str(port)
        for line in tmpFile:
            line = line.replace('{{{projectDir}}}',trunkPath + 'project/')
            line = line.replace('{{{wsgi}}}',trunkPath + 'project/apache/otg.wsgi')
            line = line.replace('{{{port}}}',port)
            apacheConf.write(line)
        tmpFile.close()
        apacheConf.close()
        os.symlink(trunkPath + 'project/apache/otg.apache.conf','/etc/apache2/sites-enabled/otg')
        portsConf = open('/etc/apache2/ports.conf','a+')
        portsConf.write('#{{{auto-gen-start}}}\nNameVirtualHost *:' + port)
        portsConf.write('Listen ' + port + '\n#{{{auto-gen-stop}}}')
        portsConf.close
        tmpFile = open('project/apache/otg.wsgi.tmp','r')
        wsgiFile = open('project/apache/otg.wsgi','w')
        for line in tmpFile:
            line = line.replace('{{{currDir}}}',os.path.abspath('project/apache/'))
            wsgiFile.write(line)
        tmpFile.close()
        wsgiFile.close()
        os.system('service apache2 restart')
    else:
        print 'Exiting'

def installWin():
    pathToVirtualenvFile = "virtualenv\\virtualenv.py "
    pathToPython = ".virtualenv\\Scripts\\python.exe "
    pathToPip = ".virtualenv\\Scripts\\pip-script.py "
    pathToManage = "project\\manage.py "
    if os.path.isdir(DestDir):
        response = input('.virtualenv folder is already created, erase and create new? (y/n): ')
        if y in response:
            shutil.rmtree('.virtualenv')
            os.system("python " + pathToVirtualenvFile + veFlags + veDestDir)
            os.system(pathToPython + pathToPip + "install " + pipFlags)
    else:
        os.system("python " + pathToVirtualenvFile + veFlags + veDestDir)
        os.system(pathToPython + pathToPip + "install " + pipFlags)
    os.system(pathToPython + pathToManage + "syncdb")

def clean():
    if os.path.isdir('.virtualenv'):
        shutil.rmtree('.virtualenv')
        print "removed .virtualenv directory"
    else:
        print "no .virtualenv directory"
        
    portsConf = open('/etc/apache2/ports.conf')
    tmp = open('/tmp/ports.tmp','w')
    stopWriting = False
    for line in portsConf:
        if '{{{auto-gen-start}}}' in line:
            stopWriting = True
        elif '{{{auto-gen-stop}}}' in line:
            stopWriting = False
        if not stopWriting:
            tmp.write(line)
            
    portsConf.close()
    tmp.close()
    os.remove('/etc/apache2/ports.conf')
    print "deleted old ports.conf"
    shutil.move('/tmp/ports.tmp','/etc/apache2/ports.conf')
    print "moved new ports.conf"
    os.remove('/etc/apache2/sites-enabled/otg')
    print "deleted apache conf for otg, restarting apache"
    os.system('service apache2 restart')

def installer():
    pathToVirtualenvFile = "virtualenv/virtualenv.py "
    veFlags = "--no-site-packages "
    veDestDir = ".virtualenv "
    pipFlags = "-r requirements.txt "
    if os.name=='posix':
        installLinux(pathToVirtualenvFile,veFlags,veDestDir,pipFlags)
    else:
        installWin()

import os, sys
import shutil
if len(sys.argv)>1:
    target = sys.argv[1]
    if target =='clean':
        clean()
    elif target=='apache':
        setupApacheInUbuntu()
    elif target=='setup':
        installer()
    elif target == 'all':
        setupApacheInUbuntu()
        installer()
    else:
        print 'Error: Unrecognized command'
else:
    installer()
